package com.yix.admin.modules.system.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.yix.admin.modules.system.entity.SysMenu;
import com.yix.admin.modules.system.entity.dto.SysMenuDto;
import com.yix.admin.modules.system.entity.dto.SysUserDto;
import com.yix.admin.modules.system.entity.mapper.SysMenuMapper;
import com.yix.admin.modules.system.entity.query.SysMenuQuery;
import com.yix.admin.modules.system.service.SysMenuService;
import com.yix.admin.modules.system.service.SysRoleService;
import com.yix.admin.modules.system.service.SysUserService;
import com.yix.common.annotation.Log;
import com.yix.common.exception.BadRequestException;
import com.yix.common.utils.PageUtil;
import com.yix.common.utils.SecurityUtils;
import com.yix.logging.annotation.LogAop;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wdx
 * @version 1.0
 * @Description TODO
 * @date 2021/1/27 16:39
 */
@Api(tags = "系统：菜单管理")
@RestController
@RequestMapping("/api/menus")
@SuppressWarnings("unchecked")
public class SysMenuController {
    @Autowired
    private SysUserService userService;
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysMenuMapper sysMenuMapper;

    private static final String ENTITY_NAME = "menu";

    @GetMapping(value = "/build")
    @ApiOperation("获取前端所需菜单")
    public ResponseEntity<Object> buildMenus(){
        List<SysMenuDto> menuDtoList = sysMenuService.findByUser(SecurityUtils.getCurrentUserId());
        List<SysMenuDto> menuDtos = sysMenuService.buildTree(menuDtoList);
        return new ResponseEntity<>(sysMenuService.buildMenus(menuDtos),HttpStatus.OK);
    }

    @GetMapping
    @ApiOperation("查询菜单")
    @PreAuthorize("@el.check('menu:list')")
    public ResponseEntity<Object> getMenus(SysMenuQuery criteria) throws Exception {
        List<SysMenuDto> menuDtoList = sysMenuService.queryAll(criteria, true);
        return new ResponseEntity<>(PageUtil.toPage(menuDtoList, menuDtoList.size()),HttpStatus.OK);
    }

    @LogAop("新增菜单")
    @ApiOperation("新增菜单")
    @PostMapping
    @PreAuthorize("@el.check('menu:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody SysMenu resources){
        if (resources.getId() != null) {
            throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
        }
        sysMenuService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @ApiOperation("查询菜单:根据ID获取同级与上级数据")
    @PostMapping("/superior")
    @PreAuthorize("@el.check('menu:list')")
    public ResponseEntity<Object> getSuperior(@RequestBody List<String> ids) {
        Set<SysMenuDto> menuDtos = new LinkedHashSet<>();
        if(CollectionUtil.isNotEmpty(ids)){
            for (String id : ids) {
                SysMenuDto menuDto = sysMenuService.findById(id);
                menuDtos.addAll(sysMenuService.getSuperior(menuDto, new ArrayList<>()));
            }
            return new ResponseEntity<>(sysMenuService.buildTree(new ArrayList<>(menuDtos)),HttpStatus.OK);
        }
        return new ResponseEntity<>(sysMenuService.getMenus(null),HttpStatus.OK);
    }

    @ApiOperation("返回全部的菜单")
    @GetMapping(value = "/lazy")
    @PreAuthorize("@el.check('menu:list','roles:list')")
    public ResponseEntity<Object> lazy(@RequestParam String pid){
        return new ResponseEntity<>(sysMenuService.getMenus(pid),HttpStatus.OK);
    }

    @Log("修改菜单")
    @ApiOperation("修改菜单")
    @PutMapping
    @PreAuthorize("@el.check('menu:edit')")
    public ResponseEntity<Object> update(@Validated(SysMenu.Update.class) @RequestBody SysMenu resources){
        sysMenuService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("删除菜单")
    @ApiOperation("删除菜单")
    @DeleteMapping
    @PreAuthorize("@el.check('menu:del')")
    public ResponseEntity<Object> delete(@RequestBody Set<String> ids){
        Set<SysMenu> menuSet = new HashSet<>();
        for (String id : ids) {
            List<SysMenuDto> menuList = sysMenuService.getMenus(id);
            menuSet.add(sysMenuService.findOne(id));
            menuSet = sysMenuService.getChildMenus(sysMenuMapper.toEntity(menuList), menuSet);
        }
        sysMenuService.delete(menuSet);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation("根据菜单ID返回所有子节点ID，包含自身ID")
    @GetMapping(value = "/child")
    @PreAuthorize("@el.check('menu:list','roles:list')")
    public ResponseEntity<Object> child(@RequestParam String id){
        Set<SysMenu> menuSet = new HashSet<>();
        List<SysMenuDto> menuList = sysMenuService.getMenus(id);
        menuSet.add(sysMenuService.findOne(id));
        menuSet = sysMenuService.getChildMenus(sysMenuMapper.toEntity(menuList), menuSet);
        Set<String> ids = menuSet.stream().map(SysMenu::getId).collect(Collectors.toSet());
        return new ResponseEntity<>(ids,HttpStatus.OK);
    }
}
